import {Button, Form, Input, Modal, Tabs, TabsProps} from "antd";
import ClassCard from "@/pages/StudentMyClassRoom/ClassCard";
import search from "@/static/imgs/TeacherMyClassroom/搜索 (1).svg";
import {useEffect, useState} from "react";
import {changeArchive, getArchiveCourse, getLearnCourse, getTopCourse, JoinCourse} from "@/api/student/courseApi";
import ClassBox from "@/pages/StudentMyClassRoom/ClassBox";
import StudentMyClassRoomNav from "@/pages/StudentMyClassRoom/StudentMyClassRoomNav";
import Wrapper from './style'
import ArchiveManagement from "@/components/ArchiveManagement";

interface Course {
    title: string;
    course: any;
}

function categorizeCourses(data: any) {
    const result: any = {};

    data.forEach((course: any) => {
        const title = `${course.semester} ${course.academicYear}`;
        if (!result[title]) {
            result[title] = [];
        }

        result[title].push(course);
    });

    const categorizedCourses = Object.keys(result).map(title => ({
        title: title,
        course: result[title]
    }));

    return categorizedCourses;
}

const StudentMyClassRoom = () => {

    const [topCourse, setTopCourse] = useState([]); // 置顶课程
    const [learnCourse, setLearnCourse] = useState<Course[]>(); // 我学的课程
    const [archiveCourse, setArchiveCourse] = useState<Course[]>(); // 归档课程

    const [isArchivedChange, setIsArchivedChange] = useState(false)

    useEffect(() => {
        if (isArchivedChange) {
            initCourse()
            setIsArchivedChange(false)
        }
    }, [isArchivedChange])

    const initCourse = () => {
        getTopCourse().then(res => {
            setTopCourse(res.data.data)
        })
        getLearnCourse().then(res => {
            const learningClass = res.data.data
            setLearnCourse(categorizeCourses(learningClass))
        })
        getArchiveCourse().then(res => {
            const archiveClass = res.data.data
            setArchiveCourse(categorizeCourses(archiveClass))
        })
    }

    useEffect(() => {
        initCourse()
    }, [])

    const onChange = (key: string) => {
        console.log(key);
    };

    const items: TabsProps['items'] = [
        {
            key: '1',
            label: '我学的',
            children: (
                <>
                    {
                        learnCourse?.map((item: any) => {
                            return <ClassBox title={item.title}>
                                {item.course.map((item: any) => {
                                    return <ClassCard key={item.id} courseId={item.id} academicYear={item.academicYear}
                                                      semester={item.semester}
                                                      name={item.name} teachClass={item.teachClass} code={item.code}
                                                      bg={item.bg}
                                                      userName={item.createUser}
                                                      isTop={item.isTop}
                                                      isArchived={item.isArchived}
                                                      initCourse={initCourse}
                                    />
                                })}
                            </ClassBox>
                        })
                    }
                </>
            ),
        },
    ];

    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        JoinCourse(form.getFieldValue('code')).then(() => {
            initCourse()
            setIsModalOpen(false);
        })
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const [form] = Form.useForm();

    const [isArchivedModelOpen, setIsArchivedModelOpen] = useState(false);
    const showArchivedModel = () => {
        console.log(archiveCourse)
        setIsArchivedModelOpen(true);
    };
    const handleArchivedOk = () => {
        setIsArchivedModelOpen(false);
    }
    const handleArchivedCancel = () => {
        initCourse()
        setIsArchivedModelOpen(false);
    }

    return (
        <Wrapper>
            <StudentMyClassRoomNav/>
            <Modal title="归档管理" open={isArchivedModelOpen} onOk={handleArchivedOk} cancelText={'取消'}
                   onCancel={handleArchivedCancel}
                   okText={'确认'}
                   width={700}
            >
                <ArchiveManagement archiveCourse={archiveCourse} setIsArchivedChange={setIsArchivedChange}
                                   changeArchive={changeArchive}/>
            </Modal>
            <Modal title="加入课程" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} cancelText={'取消'}
                   okText={'确认'}>
                <Form
                    form={form}
                    name="basic"
                    autoComplete="off"
                >
                    <Form.Item
                        label="课程码"
                        name="code"
                        rules={[{required: true, message: '请输入课程码!'}]}
                    >
                        <Input placeholder={'请输入课程加课码'}/>
                    </Form.Item>
                </Form>
            </Modal>
            <div className="home">
                <div className="content">
                    <div className="header">
                        <div className="top-handler">
                            <h2 className="left">置顶课程</h2>
                            <Button type="primary" onClick={showModal}>加入课程</Button>
                        </div>
                        <div className="class-box">
                            {
                                topCourse?.map((item: any) => {
                                    return <ClassCard key={item.id} courseId={item.id} academicYear={item.academicYear}
                                                      semester={item.semester}
                                                      name={item.name} teachClass={item.teachClass} code={item.code}
                                                      userName={item.createUser}
                                                      bg={item.bg}
                                                      isTop={item.isTop}
                                                      isArchived={item.isArchived}
                                                      initCourse={initCourse}
                                    />
                                })
                            }
                        </div>
                    </div>

                    <div className="other-header">
                        <div className="left">
                            <Tabs defaultActiveKey="1" items={items} onChange={onChange}/>
                        </div>
                        <div className="right">
                            <Button onClick={showArchivedModel}>归档管理</Button>
                            <div className="search">
                                <input type="text" placeholder={'搜索我教的课程'}/>
                                <img src={search} alt=""/>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </Wrapper>
    );
}
export default StudentMyClassRoom;